# Copyright 2009 http://www.yuntien.com
# Licensed under the Apache License, Version 2.0

from google.appengine.ext import db
from google.appengine.api import memcache
from tag import *
from user import *
from ytbase.setting import *

TAG_SPLITTER = '/'

class YTPost(db.Model):
    category = db.StringProperty(multiline=False)
    ref = db.ReferenceProperty(collection_name='ytpost_ref_set') 
    ext = db.ReferenceProperty(collection_name='ytpost_ext_set') 

    author = db.ReferenceProperty(YTUser, required=True)
    title = db.StringProperty(multiline=False)
    content = db.TextProperty()
    date = db.DateTimeProperty(auto_now_add=True)
    update = db.DateTimeProperty(auto_now=True)
  
    tags = db.StringListProperty()
    points = db.IntegerProperty(default=0)
    hot = db.BooleanProperty(default=False)
  
    def get_parent(self):
        if db.get(YTPost.ref.get_value_for_datastore(self.ref)):
            return self.ref
        return None
  
    def get_owner(self):
        return self.author
  
    def delete(self):
        YTTag.remove_tags(self.tags)
        db.Model.delete(self)
    
    def put(self):
        self.add_tags_to_db()    
        db.Model.put(self)

    def add_tags(self, tag_str):
        self._tag_str = tag_str

    def add_tags_to_db(self):
        if not hasattr(self, '_tag_str'):
            return
  
        if self._tag_str == self.get_tag_str():
            return
      
        #tag max number should be less than 10, for better performance
        tags = self._tag_str.split(TAG_SPLITTER)[0:MAX_TAG_NUM]
        #remove invalid tag
        tags = [tag for tag in tags if tag != '']
        #to add
        tags_new = [tag for tag in tags if tag not in self.tags]
        #to delete
        tags_old = [tag for tag in self.tags if tag not in tags]
        
        YTTag.add_tags(tags_new)
        YTTag.remove_tags(tags_old)
        
        self.tags = tags
  
    def get_tag_str(self):
        return TAG_SPLITTER.join(self.tags[0:MAX_TAG_NUM])
